<?php


namespace app\api\controller\v1;

use app\api\common\Iconv;
use app\api\exception\BaseException;
use app\api\validate\ClassScene;
use app\api\validate\SystemScene;
use think\exception\ValidateException;
use think\facade\Db;
use think\facade\Filesystem;
use think\facade\Request;

/**
 * Class System
 * @package app\api\controller\v1
 * 系统管理 【超级管理员】
 */
class System extends BaseException
{


    protected $noAuth = ["upload", "uploadImage", "getSystemInfo","setOrderStatus"];


    /**
     * 【超级管理员】
     * 更新系统信息
     *
     */
    public function updateSystemInfo()
    {
        $request = Request::param();
        try {
            validate(SystemScene::class)
                ->scene('update')
                ->check($request);
        } catch (ValidateException $e) {
            // 验证失败 输出错误信息
            return self::Error(null, $e->getError(), 404);
        }
        $update = [
            "system_name" => $request["system_name"],
            "system_logo" => empty($request["system_logo"]) ? '' : $request["system_logo"],
            //   "system_icon" => empty($request["system_icon"])? '' :$request["system_icon"],
            "system_telephone" => empty($request["system_telephone"]) ? '' : $request["system_telephone"],
        ];
        $check = Db::name("system")->where(["id" => 1])->update($update);
        if ($check) {
            return self::Success(null, "更新成功", 200);
        } else {
            return self::Error(null, '更新失败或已更新', 10002);
        }
    }

    public function upload()
    {
        $file = Request::file('file_upload');
        if (!$file) {
            return $this->Error("", "请上传文件", "0");
        }
        //验证文件规则
        $result = validate(['file' => ['fileSize:41943040,fileExt:gif,jpg,png,mp3,mp4']])->check(['file' => $file]);
        $filePath = '';
        if ($result) {
            //上传到服务器,
            $path = Filesystem::disk('public')->putFile('upload', $file);
            //结果是 $path = upload/20200825\***.jpg

            //图片路径，Filesystem::getDiskConfig('public','url')功能是获取public目录下的storage，
            $filePath = Filesystem::getDiskConfig('public', 'url') . '/' . str_replace('\\', '/', $path);
            //结果是 $picCover = storage/upload/20200825/***.jpg

            //获取图片名称
            $fileName = $file->getOriginalName();
        }


        return $this->Success($filePath, "上传成功", 200);
    }

    /**
     * @return \think\Response
     */
    public function uploadImage()
    {
        $file = Request::file('file_upload');
        $request = Request::param();
        if (!$file) {
            return $this->Error("", "请上传文件", "0");
        }

        //验证文件规则
        $result = validate(['file' => ['fileSize:41943040,fileExt:gif,jpg,png,mp3,mp4']])->check(['file' => $file]);
        $filePath = '';

        if ($result) {
            //上传到服务器,
            $path = Filesystem::disk('public')->putFile('upload', $file);
            //结果是 $path = upload/20200825\***.jpg

            //图片路径，Filesystem::getDiskConfig('public','url')功能是获取public目录下的storage，
            $filePath = Filesystem::getDiskConfig('public', 'url') . '/' . str_replace('\\', '/', $path);

//            if ($im = imagecreatefrompng($file) or $im = imagecreatefromgif($file) or $im = imagecreatefromjpeg($file)){
//                $imginfo = getimagesize($_FILES['upimage']['tmp_name']);
//                $resize_im = imagecreatetruecolor(32, 32);
//
//                $size = 32;
//                imagecopyresampled($resize_im, $im, 0, 0, 0, 0, $size, $size, $imginfo[0], $imginfo[1]);
//
//                $icon = new Iconv();
//
//                $gd_image_array = array($resize_im);
//
//                $icon_data = $icon->GDtoICOstr($gd_image_array);
//                $path1 = Filesystem::disk('public')->putFile('upload', $icon_data);
//                //结果是 $path = upload/20200825\***.jpg
//
//                //图片路径，Filesystem::getDiskConfig('public','url')功能是获取public目录下的storage，
//                $filePath = Filesystem::getDiskConfig('public', 'url') . '/' . str_replace('\\', '/', $path1);
//            }


            $fileName = $file->getOriginalName();
        }
        return $this->Success($filePath, "上传成功", 200);
    }

    public function getFinanceLoginLog()
    {
        $data = Request::param();
        $order = ["id" => "asc"];
        if ($data["sort"] == "+id") {
            $order = ["id" => "asc"];
        } else {
            $order = ["id" => "desc"];
        }
        $search = [];
        if (isset($data["username"]) || !empty($data["username"])) {
            $search[] = ["username", "like", "%" . $data["username"] . "%"];
        }
        if (isset($data["user_type"]) && $data["user_type"] != '') {
            array_push($search, ["user_type", "=", $data["user_type"]]);
        }
        $logList = Db::name("login_log")->where($search)->order($order)->field("id,user_id,user_type,username,ip,create_time,real_address")->page($data["page"], $data["limit"])->select();
        $count = Db::name("login_log")->count();
        $list = [
            "total" => $count,
            "page" => $data["page"],
            "limit" => $data["limit"],
            "list" => $logList
        ];
        return self::Success($list, "获取成功", 200);
    }

    public function getSystemInfo()
    {
        $systemInfo = Db::name("system")->where(["id" => 1])->find();
        $systemInfo["system_icon"] = "http://" . $_SERVER['HTTP_HOST'] . $systemInfo["system_icon"];
        $systemInfo["system_logo"] = "http://" . $_SERVER['HTTP_HOST'] . $systemInfo["system_logo"];
        return self::Success($systemInfo, "获取成功", 200);
    }

    //最新登录日志用户自身、最新报销审核状态、最新退款审核状态、最新售后状态、最近下单（10条）
    public function getUserBaseData()
    {
        $loginloglist = Db::name("login_log")->where(["user_id" => $this->user_id])->order("id desc")->page(1, 10)->select();
        $reimburselist = Db::name("reimburse")->where(["user_id" => $this->user_id])->order("id desc")->page(1, 10)->select();
        $reimbursecount = Db::name("reimburse")->where(["user_id" => $this->user_id])->count();
        $refundlist = Db::name("refund")->where(["user_id" => $this->user_id])->order("id desc")->page(1, 10)->select();
        $refundcount = Db::name("refund")->where(["user_id" => $this->user_id])->count();
        $aftersaleslist = Db::name("after_sales")->where(["user_id" => $this->user_id])->order("id desc")->page(1, 10)->select();
        $aftersalescount = Db::name("after_sales")->where(["user_id" => $this->user_id])->count();
        $orderslist = Db::name("orders")->where(["user_id" => $this->user_id])->order("id desc")->page(1, 10)->select();
        $orderscount = Db::name("orders")->where(["user_id" => $this->user_id])->count();
        $data = [
            "loginloglist" => $loginloglist,
            "reimburselist" => $reimburselist,
            "refundlist" => $refundlist,
            "aftersaleslist" => $aftersaleslist,
            "orderslist" => $orderslist,
            "reimbursecount" => $reimbursecount,
            "refundcount" => $refundcount,
            "aftersalescount" => $aftersalescount,
            "orderscount" => $orderscount,
        ];
        return self::Success($data, "获取成功", 200);
    }

    //最新登录全局登录日志、最新报销审核状态、最新退款审核状态、最新售后状态、最近下单
    public function getAdminBaseData()
    {
        $loginloglist = Db::name("login_log")->order("id desc")->page(1, 10)->select();
        $reimburselist = Db::name("reimburse")->order("id desc")->page(1, 10)->select();
        $refundlist = Db::name("refund")->order("id desc")->page(1, 10)->select();
        $aftersaleslist = Db::name("after_sales")->order("id desc")->page(1, 10)->select();
        $orderslist = Db::name("orders")->order("id desc")->page(1, 10)->select();
        $data = [
            "loginloglist" => $loginloglist,
            "reimburselist" => $reimburselist,
            "refundlist" => $refundlist,
            "aftersaleslist" => $aftersaleslist,
            "orderslist" => $orderslist,
        ];
        return self::Success($data, "获取成功", 200);
    }


    public function getAddress(){
        $data = Request::param();
        //获取 access_token
        $url = 'https://aip.baidubce.com/oauth/2.0/token';
        $post_data['grant_type']       = 'client_credentials';
        $post_data['client_id']      = 'RrvitpuARmyVtqjZf7WpuZC4';
        $post_data['client_secret'] = 'GeqxPl9y5jQXs8PvR9MUXAzdayn669cc';
        $o = "";
        foreach ( $post_data as $k => $v )
        {
            $o.= "$k=" . urlencode( $v ). "&" ;
        }
        $post_data = substr($o,0,-1);
        $res = $this->request_post($url, $post_data);
        $res=json_decode($res,TRUE);
        $access_token=$res['access_token'];
//
////地址识别
        $url="https://aip.baidubce.com/rpc/2.0/nlp/v1/address";
        $url = $url.'?access_token=' . $access_token.'&charset=UTF-8';
        $bodys = array(
            'text' => $data["address_content"],
            'confidence' => 80,
        );
        $res = $this->request_post($url, json_encode($bodys));

        return self::Success(   json_decode($res), "获取成功", 200);

    }


    function request_post($url = '', $param = '')
    {
        if (empty($url) || empty($param)) {
            return false;
        }

        $postUrl = $url;
        $curlPost = $param;
        // 初始化curl
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $postUrl);
        curl_setopt($curl, CURLOPT_HEADER, 0);
        // 要求结果为字符串且输出到屏幕上
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        // post提交方式
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $curlPost);
        // 运行curl
        $data = curl_exec($curl);
        curl_close($curl);

        return $data;
    }



    public function setOrderStatus()
    {
        $orderList = Db::name("orders")->where(["data_state" => 1, "status" => 0])->select()->toArray();
        foreach ($orderList as $key => $value) {
            $updateData = [
                "status" => 1,
                'update_time' => date("Y-m-d H:i:s", time()),
            ];
            Db::name("orders")->where(["id" => $value["id"]])->update($updateData);
        }
        var_dump($orderList);

    }
}